<template>
  <el-dialog v-model="dialogVisible" title="维修任务列表" width="90%" top="5vh" @close="handleClose">
    <!-- 搜索工作栏 -->
    <!--     <ContentWrap>
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="维修单号" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入维修单号" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>

        <el-form-item label="故障分类" prop="faultId">
          <el-select v-model="queryParams.faultId" placeholder="请选择故障分类" clearable class="!w-240px">
            <el-option v-for="cat in repairCategories" :key="cat.id" :label="cat.name" :value="cat.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="申请人" prop="applicantId">
          <el-select v-model="queryParams.applicantId" filterable clearable placeholder="请选择申请人" class="!w-240px">
            <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="申请时间" prop="applicationTime">
          <el-date-picker v-model="queryParams.applicationTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
            start-placeholder="开始日期" end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
            <el-option v-for="status in repairStatusOptions" :key="status.value" :label="status.label"
              :value="status.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" /> 搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> 重置
          </el-button>
          <el-button type="success" plain @click="handleExport" :loading="exportLoading"
            v-hasPermi="['mold:repair-job:export']">
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap> -->

    <!-- 列表 -->
    <ContentWrap>
      <el-table row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange" border>
        <!--       <el-table-column type="selection" width="55" /> -->
        <el-table-column label="维修单号" align="center" prop="code">
          <template #default="scope">
            <el-button type="primary" link @click="openDetail(scope.row.id)">
              {{ scope.row.code }}
            </el-button>
          </template>
        </el-table-column>
        <!--         <el-table-column label="模具名称" align="center" prop="accountName" />
        <el-table-column label="模具编码" align="center" prop="accountCode" /> -->
        <el-table-column label="维修分类" align="center" prop="repairCategoryName" />
        <el-table-column label="故障分类" align="center" prop="faultName" />
        <el-table-column label="申请人" align="center" prop="applicantName" />
        <el-table-column label="申请部门" align="center" prop="departName" />
        <el-table-column label="下达时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
        <el-table-column label="接收时间" align="center" prop="jobReceiveTime" :formatter="dateFormatter" width="180px" />
        <el-table-column label="故障描述" align="center" prop="faultDescription" width="120">
          <template #default="scope">
            <div class="rich-text-content" v-html="scope.row.faultDescription"></div>
          </template>
        </el-table-column>
        <el-table-column label="任务状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.MOLD_REPAIR_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
        <el-table-column label="操作" align="center" min-width="150px">
          <template #default="scope">
            <el-button link type="primary" @click="openDetail(scope.row.id)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
    </ContentWrap>

    <!-- 表单弹窗：报工界面 -->
    <RepairJobWorkPort ref="workPortRef" @success="getList" />

    <!-- 表单弹窗：详情界面 -->
    <RepairJobDetail ref="detailRef" />
  </el-dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { RepairJobApi, RepairJob, RepairJobModStatus } from '@/api/mold/repairjob'
import RepairJobWorkPort from '@/views/mold/repairjob/RepairJobWorkPort.vue'
import RepairJobDetail from '@/views/mold/repairjob/RepairJobDetail.vue'
import { RepairFaultCategoryApi } from '@/api/mold/repairfaultcategory'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from '@/hooks/web/useI18n'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const dialogVisible = ref(false)
const loading = ref(true) // 列表的加载中
const list = ref<RepairJob[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const exportLoading = ref(false) // 导出的加载中
const accountId = ref<number>() // 传递进来的模具ID

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  accountId: undefined,
  repairCategoryId: undefined,
  faultId: undefined,
  applicantId: undefined,
  departId: undefined,
  applicationTime: [],
  faultDescription: undefined,
  status: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const repairCategories = ref([])
const userList = ref<UserVO[]>([])
const workPortRef = ref()
const detailRef = ref()

// 维修状态选项
const repairStatusOptions = [
  { value: 1, label: '待分配' },
  { value: 2, label: '已分配' },
  { value: 3, label: '已接收' },
  { value: 4, label: '进行中' },
  { value: 5, label: '已完成' },
  { value: 6, label: '已关闭' }
]

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 强制设置accountId查询条件
    queryParams.accountId = accountId.value
    const data = await RepairJobApi.getRepairJobPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  // 保留accountId条件
  queryParams.accountId = accountId.value
  handleQuery()
}

/** 接收维修任务 */
const handleReceive = (id: number) => {
  const status_a: RepairJobModStatus = {
    id: id,
    status: 3,
    data: ""
  }
  modStatus(status_a)
}

/** 开始作业 */
const handleStartJob = (id: number) => {
  message.confirm('确认开始作业吗？').then(() => {
    const status_a: RepairJobModStatus = {
      id: id,
      status: 4,
      data: ""
    }
    modStatus(status_a)
  })
}

/** 打开报工界面 */
const handleWorkPort = (id: number) => {
  workPortRef.value.open(id)
}

/** 打开维修任务详情 */
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 修改维修任务状态 */
const modStatus = async (s: RepairJobModStatus) => {
  try {
    await RepairJobApi.modStatus(s)
    message.success('操作成功')
    await getList()
  } catch (error) {
    message.error('操作失败')
  }
}

/** 删除维修任务 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RepairJobApi.deleteRepairJob(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: RepairJob[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RepairJobApi.exportRepairJob(queryParams)
    download.excel(data, '维修任务.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const getRepairCategories = async () => {
  repairCategories.value = []
  const data = await RepairFaultCategoryApi.getRepairFaultCategoryAll()
  repairCategories.value = handleTree(data)
}

const getUserList = async () => {
  userList.value = await UserApi.getSimpleUserList()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 打开对话框并传入模具ID
const open = async (id: number) => {
  accountId.value = id
  queryParams.accountId = id
  dialogVisible.value = true
  await Promise.all([
    getRepairCategories(),
    getUserList()
  ])
  await getList()
}

// 暴露方法给父组件
defineExpose({
  open
})
</script>

<style scoped>
.rich-text-content {
  line-height: 1.6;
}
</style>